//
//  NetConnectInfo.m
//  AQ800
//
//  Created by 赵武 on 13-12-10.
//  Copyright (c) 2013年 杭州茂葳科技有限公司. All rights reserved.
//

#import "NetConnectInfo.h"
#import "getgateway.h"
#import <arpa/inet.h>
#import <netdb.h>

@implementation NetConnectInfo


// 获取wifi配置的目标地址
- (NSString *) GetConfigAddress
{
    struct in_addr addr;
    getdefaultgateway(&(addr.s_addr));
    NSString *addrStr = [NSString stringWithUTF8String:inet_ntoa(addr)];
    NSLog(@"net dev name = %@", addrStr);
    return addrStr;
}

// 获取wifi ip地址，获取成功返回地址信息，获取失败返回nil
- (NSString *) LocalWiFiIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"] || [name isEqualToString:@"en1"])  // Wi-Fi适配器为en0或en1
                {
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

@end
